package com.shaoshaohuo.app.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.service.LocationService;
import com.amap.api.maps2d.model.LatLng;

/**
 * 定位工具
 * Created by YinSF on 16/1/25.
 */
public class Location2Util implements AMapLocationListener {
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private Intent alarmIntent = null;
    private PendingIntent alarmPi = null;
    private AlarmManager alarm = null;

    private static final String ACTION_NAME = "www.tinamaoetong.location";

    private Context context;
    private static final long alarmInterval = 60;//秒

    private OnLocationListener locationListener;

    private LocationService service;

    private static Location2Util instance;

    public static Location2Util getInstance(Context context) {
        if (instance == null) {
            instance = new Location2Util(context);
        }
        return instance;
    }

    public Location2Util(Context context) {
        this.context = context;


        //动态注册一个广播
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ACTION_NAME);
//        context.registerReceiver(alarmReceiver, filter);
    }

    private void initLocationOption() {
        locationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
//        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //低精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);

        // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
//        locationOption.setInterval(alarmInterval * 1000);
        //需要逆地里编码
        locationOption.setNeedAddress(true);
        //设置为单次定位
        locationOption.setOnceLocation(true);
    }

    public void startLocation() {
        // 创建Intent对象，action为LOCATION
        alarmIntent = new Intent(context, LocationService.class);
        alarmIntent.setAction(ACTION_NAME);

        // 定义一个PendingIntent对象，PendingIntent.getBroadcast包含了sendBroadcast的动作。
        // 也就是发送了action 为"LOCATION"的intent
        alarmPi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // AlarmManager对象,注意这里并不是new一个对象，Alarmmanager为系统级服务
        alarm = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        //设置一个闹钟，2秒之后每隔一段时间执行启动一次定位程序
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2 * 1000,
                alarmInterval * 1000, alarmPi);
    }

    public void doOnceLocation() {
        locationClient = new AMapLocationClient(context);
        initLocationOption();
        // 设置定位监听
        locationClient.setLocationListener(this);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
        mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Utils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    public void setOnLocationListener(OnLocationListener locationListener) {
        this.locationListener = locationListener;
    }

    public void destroy() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }

    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //开始定位
                case Utils.MSG_LOCATION_START:
                    break;
                // 定位完成
                case Utils.MSG_LOCATION_FINISH:
                    AMapLocation loc = (AMapLocation) msg.obj;
                    SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.LNG, loc.getLongitude() + "");
                    SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.LAT, loc.getLatitude() + "");
                    if (locationListener != null) {
                        locationListener.onLocationSuccess(loc);
                    }
                    LogUtil.i("Location", getLocationStr(loc));
                    RequestService.getInstance().reportGeo(context, loc.getLongitude() + "", loc.getLatitude() + "", BaseEntity.class, new HttpRequest.RequestListener() {

                        @Override
                        public void onSuccess(int requestCode, BaseEntity resultData) {
                        }

                        @Override
                        public void onFailed(int requestCode, Exception error, String msg) {
                        }
                    });
                    destroy();
                    break;
                //停止定位
                case Utils.MSG_LOCATION_STOP:
                    break;
                default:
                    break;
            }
        };
    };

    public static void geoSearch(Context context, double lat, double lng, GeocodeSearch.OnGeocodeSearchListener listener) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(context);
        geocoderSearch.setOnGeocodeSearchListener(listener);
//latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
        LatLonPoint latLonPoint = new LatLonPoint(lat, lng);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500,GeocodeSearch.GPS);
        geocoderSearch.getFromLocationAsyn(query);
    }

    public synchronized static String getLocationStr(AMapLocation location){
        if(null == location){
            return null;
        }
        StringBuffer sb = new StringBuffer();
        //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
        if(location.getErrorCode() == 0){
            sb.append("定位成功" + "\n");
            sb.append("定位类型: " + location.getLocationType() + "\n");
            sb.append("经    度    : " + location.getLongitude() + "\n");
            sb.append("纬    度    : " + location.getLatitude() + "\n");
            sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
            sb.append("提供者    : " + location.getProvider() + "\n");

            if (location.getProvider().equalsIgnoreCase(
                    android.location.LocationManager.GPS_PROVIDER)) {
                // 以下信息只有提供者是GPS时才会有
                sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                sb.append("角    度    : " + location.getBearing() + "\n");
                // 获取当前提供定位服务的卫星个数
                sb.append("星    数    : "
                        + location.getSatellites() + "\n");
            } else {
                // 提供者是GPS时是没有以下信息的
                sb.append("国    家    : " + location.getCountry() + "\n");
                sb.append("省            : " + location.getProvince() + "\n");
                sb.append("市            : " + location.getCity() + "\n");
                sb.append("城市编码 : " + location.getCityCode() + "\n");
                sb.append("区            : " + location.getDistrict() + "\n");
                sb.append("区域 码   : " + location.getAdCode() + "\n");
                sb.append("地    址    : " + location.getAddress() + "\n");
                sb.append("兴趣点    : " + location.getPoiName() + "\n");
            }
        } else {
            //定位失败
            sb.append("定位失败" + "\n");
            sb.append("错误码:" + location.getErrorCode() + "\n");
            sb.append("错误信息:" + location.getErrorInfo() + "\n");
            sb.append("错误描述:" + location.getLocationDetail() + "\n");
        }
        return sb.toString();
    }

    /**
     * 获取两个坐标之间的距离
     * @param startLat
     * @param startLng
     * @param endLat
     * @param endLng
     * @return
     */
    public float distance(double startLat, double startLng, double endLat, double endLng) {
        LatLng startLatlng = new LatLng(startLat, startLng);
        LatLng endLatlng = new LatLng(endLat, endLng);
        return AMapUtils.calculateLineDistance(startLatlng, endLatlng);
    }
    /**
     * 获取两个坐标之间的距离
     * @param startLat
     * @param startLng
     * @param endLat
     * @param endLng
     * @return
     */
    public String distance(String startLat, String startLng, String endLat, String endLng) {
        double doubStartLat = Double.parseDouble(startLat);
        double doubStartLng = Double.parseDouble(startLng);
        double doubEndLat = Double.parseDouble(endLat);
        double doubEndLng = Double.parseDouble(endLng);
        LatLng startLatlng = new LatLng(doubStartLat, doubStartLng);
        LatLng endLatlng = new LatLng(doubEndLat, doubEndLng);
        return StringUtil.formatDouble(AMapUtils.calculateLineDistance(startLatlng, endLatlng) / 1000);
    }

    class Utils {
        /**
         * 开始定位
         */
        public final static int MSG_LOCATION_START = 0;
        /**
         * 定位完成
         */
        public final static int MSG_LOCATION_FINISH = 1;
        /**
         * 停止定位
         */
        public final static int MSG_LOCATION_STOP = 2;


    }

    public interface OnLocationListener{
        public void onLocationSuccess(AMapLocation location);
    }
}
